require "open-uri"  
require "timeout"  

=begin
     20 * * * * *  cd /home/jill/13wins && GEM_PATH=/opt/local/lib/ruby/gems:/opt/local/lib/ruby/gems/bin  /opt/local/bin/rake RAILS_ENV=production win:fetch > /home/jill/13wins/log/cron_fetch.log 2>&1
=end


namespace :win do
  desc 'UPDATE  '
  RAILS_ENV='production' 
  BASE_URL = 'http://xml.sportspunter.com/xml'
 
  #username=edwyn2&password=234567&format=xml&cid=20 
  task :fetch_matches =>:environment do 
      League.find(:all).each do |league|
        next if league.cid.nil? 
        begin
          timeout 10 do
	     response = Net::HTTP.post_form(URI.parse(BASE_URL), {'username'=>'edwyn2','password'=>'234567','format'=>'xml','cid'=>league.cid}) 
	     hash = Hash.from_xml(response.body) 
	       #league = League.find_by_cid(29)
	       #content = File.open("lib/xml.xml").read
	       #hash = Hash.from_xml(content) 
	       # p doc
	       if hash["SPORTSPUNTER"] and hash["SPORTSPUNTER"]["competition"] and hash["SPORTSPUNTER"]["competition"]["matches"]["match"] 
		  hash["SPORTSPUNTER"]["competition"]["matches"]["match"].each do |match|
		    m = Match.from_hash(match,league) 
		    puts Time.now.strftime("%Y-%m-%d %H:%M:%S") + ":match created or find: " + m.mid.to_s if m 
		  end 
	       else 
		  p "no matches" 
	       end
	   end # of timeout
       #begin of start
       rescue Timeout::Error=>e
         puts "fetch time out. skipping...." 
       rescue Exception=>e
         puts "process league#: " + league.to_s + " get unexpected exception.... "
         puts e.message.inspect 
       end
       sleep 5 
     end # of league 
  end

	task :fetch_results => :environment do
		urls = ["http://www.scorespro.com/rss/live-basketball.xml","http://www.scorespro.com/rss/live-soccer.xml"]
		urls.each do |url|
			content = open(url) do |file|
				file.read
			end
			data = Hash.from_xml(content)
		
			data["rss"]["channel"]["item"].each do |item|
				title = item["title"]
				regexp = /^FT\s*(.+?)\s*\-\s*(.+?)\s*(\d{1,3})\s*\-\s*(\d{1,3}).+?$/
				if title =~ regexp
					home_team_name,away_team_name,home_point,away_point =  $1,$2,$3,$4
				  	if !Result.exists?(["home_team = ? and away_team = ?",home_team_name,away_team_name])
				    	result = Result.new 
					    result.home_team = home_team_name 
					    result.away_team = away_team_name 
					    result.home_point = home_point
					    result.away_point = away_point
					    result.processed = false
					    result.rtype = "Football" if url.match("soccer")
					    result.rtype = "Basketball" if url.match("basketball")
					    result.save
					    puts "Result received and saved to DB:" + "#{home_team_name},#{away_team_name},#{home_point},#{away_point}"		  
					else
				 		#puts "This entry exists: " +  "#{home_team_name},#{away_team_name},#{home_point},#{away_point}"
					end
				    
				    # first lookup if name_alias exists.
				    # if name_alias does not exist, then use name given.
				    home_team = Team.find_by_name_alias(home_team_name)
				    home_team = Team.find_by_name(home_team_name) if home_team.nil?
				    away_team = Team.find_by_name_alias(away_team_name)
				    away_team = Team.find_by_name(away_team_name) if away_team.nil? 
				    
					puts "check if teams can be found:" + "#{home_team_name},#{away_team_name},#{home_point},#{away_point}"						 
				    if home_team && away_team
				    	# name_alias exists. then set alias_done to true
				     	unless home_team.alias_done
				     		home_team.alias_done = true
				      		home_team.save
				     	end
				        unless away_team.alias_done
				           home_team.alias_done = true
				           home_team.save
				        end
					puts "check if match can be found:" + "#{home_team_name},#{away_team_name},#{home_point},#{away_point}"	
						# if match exists, then process it
					    match = Match.find_by_home_team_id_and_away_team_id_and_played(home_team.id,away_team.id,false)
					    if match
					    	puts "match found: " + "#{home_team_name},#{away_team_name},#{home_point},#{away_point}"
							match.play_from_point(home_point,away_point)
					        puts "Match is processed:" + "#{home_team_name},#{away_team_name},#{home_point},#{away_point}"
					 	else	
							puts "Match not processed:" + "#{home_team_name},#{away_team_name},#{home_point},#{away_point}"
					 	end				     
				 	end		
				end
		    end
		end
	end
end
